package com.jarvis.app.car;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;


import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.jarvis.app.car.common.MessageResult;
import com.jarvis.app.car.model.Car;
import com.jarvis.app.car.model.CarTrack;
import com.jarvis.app.car.util.ServiceManager;
import com.jarvis.app.car.util.ThreadPoolManager;

public class CarInfoActivity extends AppCompatActivity {

    private MapView mMapView;


    private ImageView iv_back;

    private TextView tv_carCode;

    private TextView tv_carName;

    private TextView tv_catTrack;

    private final Handler lunXunHandler = new Handler();

    private final Handler infoHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<Car> messageResult = (MessageResult<Car>) message.obj;

            if (!messageResult.isJudgeSuccess()) {
                Toast.makeText(CarInfoActivity.this, messageResult.getMsg(), Toast.LENGTH_SHORT).show();

            } else {
                Car car = messageResult.getResult();
                tv_carCode.setText(car.getCode());
                tv_carName.setText(car.getName());

            }
        }
    };
    private final Handler pointHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<CarTrack> messageResult = (MessageResult<CarTrack>) message.obj;

            if (!messageResult.isJudgeSuccess()) {
                Toast.makeText(CarInfoActivity.this, messageResult.getMsg(), Toast.LENGTH_SHORT).show();

            } else {
                CarTrack result = messageResult.getResult();
                if (result != null) {
                    //地图定位显示
                    LatLng latLng = new LatLng(Double.valueOf(result.getX_point()), Double.valueOf(result.getY_point()));
                    MapStatusUpdate status2 = MapStatusUpdateFactory.newLatLng(latLng);
                    mMapView.getMap().setMapStatus(status2);

                    BaiduMap mBaiduMap = mMapView.getMap();


                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.zoom(18.0f);
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                    //地图绘制图标
                    BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.car);
                    MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(bitmap);
                    mBaiduMap.addOverlay(markerOptions);
                }


            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_car_info);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        tv_carCode = findViewById(R.id.tv_carCode);
        tv_carName = findViewById(R.id.tv_carName);
        iv_back = findViewById(R.id.iv_back);
        tv_catTrack = findViewById(R.id.tv_catTrack);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);

        tv_catTrack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                long carId = intent.getLongExtra("carId", 0);

                Intent intentTrack = new Intent(CarInfoActivity.this, CarTrackActivity.class);
                intentTrack.putExtra("carId", carId);
                startActivityForResult(intentTrack, Integer.MIN_VALUE);
            }
        });


        Runnable roundRobinTask = new Runnable() {
            @Override
            public void run() {
                loadCarPoint();
                lunXunHandler.postDelayed(this, 30000);
            }
        };

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lunXunHandler.removeCallbacks(roundRobinTask);
                finish();
            }
        });

        loadData();
        lunXunHandler.post(roundRobinTask);


    }


    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }


    private void loadData() {
        Intent intent = getIntent();
        long carId = intent.getLongExtra("carId", 0);

        ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                MessageResult<Car> messageResult = ServiceManager.carService.getOne(carId);
                Message msg = Message.obtain();
                msg.obj = messageResult;
                infoHandler.sendMessage(msg);
            }
        });
    }


    private void loadCarPoint() {
        Intent intent = getIntent();
        long carId = intent.getLongExtra("carId", 0);

        ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                MessageResult<CarTrack> messageResult = ServiceManager.carTrackService.getLastOne(carId);
                Message msg = Message.obtain();
                msg.obj = messageResult;
                pointHandler.sendMessage(msg);
            }
        });

    }
}